//
//  FieldController.m
//  SimpleHappy
//
//  Created by lanou on 15/11/23.
//  Copyright © 2015年 RockyFung. All rights reserved.
//

#import "FieldController.h"
#import "FieldCell.h"
#import "Define.h"
#import "FieldHeader.h"
#import "DetailController.h"
#import "FieldHeaderModel.h"
#import "FieldModel.h"
#import "MJRefresh.h"
#import "SHDetailModel.h"

@interface FieldController ()


@property (nonatomic, strong) NSMutableArray *headerModelArray; // 表头数组
@property (nonatomic, strong) NSString *headerUrl; // 表头链接

@property (nonatomic, strong) NSMutableArray *lifeModelArray; // 视野数组
@property (nonatomic, strong) NSString *lifeUrl; // 视野链接
@property (nonatomic, assign) NSInteger pageNum;

@end

@implementation FieldController

// 懒加载，一般用于上拉加载更多
- (NSMutableArray *)lifeModelArray
{
    if (!_lifeModelArray) {
        self.lifeModelArray = [NSMutableArray array];
    }
    return _lifeModelArray;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    // 清除tableViewCell自带线条
    self.tableView.separatorStyle = NO;
    
    // 注册表头
    [self.tableView registerClass:[FieldHeader class] forHeaderFooterViewReuseIdentifier:@"header"];
    
    // 表头数据请求
    self.headerUrl = @"http://api.yhouse.com/m/promotion/list/6";
    [self setNetWorkRequestForHeaderWithUrlString:self.headerUrl];
    
    // 视野数据请求
    self.lifeUrl = @"http://api.yhouse.com/m/life/list?app_type=2&page=1";
    [self setNetWorkRequestForLifeWithUrlString:self.lifeUrl];
    

    // 下拉刷新
    [self.tableView addLegendHeaderWithRefreshingTarget:self refreshingAction:@selector(headerAction)];
    // 下拉加载
    [self.tableView addLegendFooterWithRefreshingTarget:self refreshingAction:@selector(footerAction)];
    
}

#pragma mark - 上拉加载更多，下拉刷新
// 下拉刷新
- (void)headerAction
{
    [self setNetWorkRequestForLifeWithUrlString:self.lifeUrl];
    [self.tableView.header endRefreshing];
}
// 上拉加载更多
- (void)footerAction
{
    self.pageNum += 1;
    self.lifeUrl = [NSString stringWithFormat:@"http://api.yhouse.com/m/life/list?app_type=2&page=%ld",_pageNum+1];
    [self setNetWorkRequestForLifeWithUrlString:self.lifeUrl];
    [self.tableView reloadData];
    [self.tableView.footer endRefreshing];
    
}


#pragma mark - Table view data source
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {

    return self.lifeModelArray.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return KScreenHeight / 6;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

    static NSString *cellIdentifier = @"cell";
    FieldCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
    if (cell == nil) {
        cell = [[FieldCell alloc]initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:cellIdentifier];
    }
    cell.model = self.lifeModelArray[indexPath.row];
    return cell;
}


// 点击cell
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    DetailController *detailVc = [[DetailController alloc]init];
    detailVc.hidesBottomBarWhenPushed = YES;
    detailVc.isDiscover = YES;
    FieldModel *model = self.lifeModelArray[indexPath.row];
    
    SHDetailModel *SHModel = [[SHDetailModel alloc]init];
    SHModel.picUrl = model.picUrl;
    SHModel.openUrl = model.openUrl;
    SHModel.title = model.title;
    detailVc.SHDetailModel = SHModel;
    
    detailVc.targetUrl = model.openUrl;
    [self.navigationController pushViewController:detailVc animated:YES];
}


#pragma mark - 表头代理方法
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return KScreenWidth / 720 * 450;
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 0.1;
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    
   FieldHeader *header = [tableView dequeueReusableHeaderFooterViewWithIdentifier:@"header"];
   header.modelArray = self.headerModelArray;
   return header;
}


#pragma mark - 表头数据请求
- (void)setNetWorkRequestForHeaderWithUrlString:(NSString *)urlString
{
    [[[NSURLSession sharedSession]dataTaskWithURL:[NSURL URLWithString:urlString] completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        
        if (error) {
            NSLog(@"网络请求错误");
            return ;
        }
        
        
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
        self.headerModelArray = [NSMutableArray array];
        for (NSDictionary *dataDic in dic[@"data"]) {
            FieldHeaderModel *model = [[FieldHeaderModel alloc]init];
            [model setValuesForKeysWithDictionary:dataDic];
            [self.headerModelArray addObject:model];
        }
        // 刷新数据
        dispatch_async(dispatch_get_main_queue(), ^{
            [self.tableView reloadData];
        });
    }]resume];
    
}

#pragma mark - 视野数据请求
- (void)setNetWorkRequestForLifeWithUrlString:(NSString *)urlString
{
    [[[NSURLSession sharedSession]dataTaskWithURL:[NSURL URLWithString:urlString] completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        
        
        if (error) {
            NSLog(@"网络请求错误");
            return ;
        }
        
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
        NSDictionary *dataDic = dic[@"data"];
        for (NSDictionary *docDic in dataDic[@"doc"]) {
            FieldModel *model = [[FieldModel alloc]init];
            [model setValuesForKeysWithDictionary:docDic];
            [self.lifeModelArray addObject:model];
        }
        // 刷新数据
        dispatch_async(dispatch_get_main_queue(), ^{
            [self.tableView reloadData];
        });
    }]resume];
}





@end
